﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using Scrubblet.FrontEnd.Models;
using Scrubblet.FrontEnd.Models.Entities;
using Game = Scrubblet.FrontEnd.Models.Game;
using DotNetOpenAuth.Messaging;
using System.Data.Entity;

namespace Scrubblet.FrontEnd.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index(string gameId)
        {
            //ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.FFFF";

            var model = new GameModel();

            using (var db = new EntitiesContext())
            {
                var user = (from u in db.UserProfiles where u.UserName == User.Identity.Name select u).FirstOrDefault();
                if (user == null) return RedirectToAction("Login", "Account");

                int iid;
                if (int.TryParse(gameId, out iid))
                {
                    var gameEntity = db.Games.FirstOrDefault(t => t.Id == iid);
                    if (gameEntity != null)
                    {
                        var game = new Game(gameEntity.Board.Configuration.Width, gameEntity.Board.Configuration.Height);

                        foreach (var gameMove in gameEntity.Moves)
                        {
                            if (gameMove.Type == GameMoveType.PutWord)
                            {
                                foreach (var putTile in gameMove.PutTiles)
                                {
                                    game[putTile.X, putTile.Y] = putTile.Tile.Symbol;
                                }
                            }
                        }

                        foreach (var cell in gameEntity.Board.SpecialCells)
                        {
                            game.CellTypes[cell.X, cell.Y] = cell.Type;
                        }

                        var player = gameEntity.Players.First(t => t.User == user);

                        game.PlayerLetters = player.TilesOnHand.Select(t => t.Symbol).ToList();

                        model.SelectedGame = game;
                    }
                }

                foreach (var game in db.Games.Where(g => g.CreatorId == user.UserId))
                {
                    model.Games.Add(new GameInfo { Id = game.Id.ToString(CultureInfo.InvariantCulture), Name = game.Name + " " + game.CreatedTime });
                }
            }

            return View(model);
        }

        private UserProfile GetCurrentUser(EntitiesContext db)
        {
            var user = (from u in db.UserProfiles where u.UserName == User.Identity.Name select u).First();
            return user;
        }

        private IEnumerable<Tile> TakeRandomTiles(ICollection<Tile> tiles, int count)
        {
            var r = new Random();
            var result = new List<Tile>();
            for (int i = 0; i < count && tiles.Count > 0; i++)
            {
                int next = r.Next(tiles.Count);
                Tile tile = tiles.ElementAt(next);
                result.Add(tile);
                tiles.Remove(tile);
            }
            return result;
        }

        public ActionResult StartNewGame(NewGameModel newGameModel)
        {
            int tileSetId = int.Parse(newGameModel.SelectedAlphabet);
            int boardId = int.Parse(newGameModel.SelectedBoard);


            using (var db = new EntitiesContext())
            {
                var game = new Models.Entities.Game();
                game.CreatedTime = DateTime.UtcNow;
                game.Creator = GetCurrentUser(db);

                game.Board = db.BoardConfigurations.First(t => t.Id == boardId).Versions.First();
                game.TileSet = db.TileSets.First(t => t.Id == tileSetId);

                game.TilesInBag.AddRange(game.TileSet.Tiles);

                var gamePlayer = new GamePlayer();
                game.Players.Add(gamePlayer);

                gamePlayer.User = game.Creator;
                gamePlayer.TilesOnHand.AddRange(TakeRandomTiles(game.TilesInBag, 7));

                game.Name = newGameModel.Name;
                db.Games.Add(game);

                db.SaveChanges();
            }

            return RedirectToAction("Index");
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult NewGame(GameModel model)
        {
            model.IsNewGame = true;

            using (var db = new EntitiesContext())
            {
                model.NewGameData.Name = "Game Name Here";
                model.NewGameData.Boards.AddRange(db.BoardConfigurations.ToList().Select(t => new GameBoard { Id = t.Id, Name = t.Name + ": " + t.Width + "x" + t.Height }));
                model.NewGameData.Alphabets.AddRange(db.TileSets.ToList().Select(t => new GameAlphabet { Id = t.Id, Name = t.Name }));
            }

            return View("Index", model);
        }
    }
}
